package com.heartech.prediciton_wx.controller;


import com.heartech.prediciton_wx.service.message.MessageService;
import com.heartech.prediciton_wx.service.message.XmlConvertService;
import com.heartech.prediciton_wx.utils.message.UserResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wxpublic")
public class WXPublicController {
    private final XmlConvertService xmlConvertService;
    private final MessageService messageService;

    @Autowired
    public WXPublicController(XmlConvertService xmlConvertService, MessageService messageService) {
        this.messageService = messageService;
        this.xmlConvertService = xmlConvertService;
    }

    @RequestMapping("/verify_wx_token")
    public void handleWxMessage(HttpServletRequest request, HttpServletResponse response) throws InstantiationException, IllegalAccessException {
        try {
            Map<String, String> paramMap = xmlConvertService.parseXml(request);
            UserResult.sendXmlResponse(messageService.processRequest(paramMap),response);
        } catch (IOException | DocumentException e) {
            // 处理异常，可以进行日志记录或其他操作
            e.printStackTrace();
            // 返回适当的错误响应
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
